/*
 * npc.c
 *
 * Controls the list of NPCs and allows each to act every turn.
 */

#include "npc.h"
#include <controller/action.h>
#include <controller/controller.h>
#include <gamelogic/event_utils.h>
#include <stdlib.h>

#define NPC_LIST_SIZE 16

static int npc_initialized = 0;
static unit npc_list[NPC_LIST_SIZE];
static int npc_count = 0;
static int npc_iterator = 0;

/*
 * Creates a new NPC with the given attributes at the given location.
 */
unit * npc_create( unsigned long x, unsigned long y, unsigned long z,
    const char *name, void *stats ) {
    if( npc_count < NPC_LIST_SIZE ) {
        npc_list[npc_count].x = x;
        npc_list[npc_count].y = y;
        npc_list[npc_count].z = z;
        npc_list[npc_count].name = name;
        npc_list[npc_count].stats = stats;
        npc_count++;
        return &(npc_list[npc_count-1]);
    }
    else {
        /* TODO: error */
        return NULL;
    }
}

/*
 * Returns the NPC ID number of the last created NPC.
 */
int npc_last_id() {
    return npc_count - 1;
}

int debug_trap( int n ) {
    if( n == 1 ) {
        return 0;
    }
    else {
        return debug_trap(1);
    }
}

/*
 * Returns the unit with the given unit ID.
 */
unit * npc_get( int id ) {
    if( id < npc_count && id >= 0 ) {
        return &(npc_list[id]);
    }
    else if( id == -1 ) {
        return &(npc_list[0]);
    }
    else {
        /* TODO: error */
        printf("Out of bounds exception in npc_get: %d\n", id);
        debug_trap(0);
        return NULL;
    }
}

/*
 * Returns the next (or first if this is the first time calling this function
 * or npc_list_reset() has been called) NPC in the NPC list. This
 * function is single-threaded and is not a true iterator, therefor it is
 * advised that npc_list_reset() is called before any invocation of
 * this function and that all work that needs to be done over this list is done
 * in a timely manner so as to not risk getting the iterator reset before all
 * work is done. Will return NULL when the list is exhausted until
 * npc_list_reset() is called.
 *
 * TL;DR version: Don't use this function.
 */
unit * npc_next() {
    unit *u;
    if( npc_iterator < npc_count ) {
        u = &(npc_list[npc_iterator]);
        npc_iterator++;
        return u;
    }
    else {
        return NULL;
    }
}

/*
 * Resets the NPC list iterator.
 */
void npc_list_reset() {
    npc_iterator = 0;
}
